trigger PlanDocStatusChange on Sales_Contract__c (after update, after insert) 
{
    List<Task> taskList = new List<Task>();
    List<Sales_Contract__Share> shareContractList = new List<Sales_Contract__Share>();
    List<CallidusDataSource__Share> dataSourceSharingList = new List<CallidusDataSource__Share>();

    String shareId = '';
    Date dt = null;
    Integer scSize = 0;
    
/*    Map<String, List<ID>> usersManagerMap = new Map<String, List<ID>>();
    List<ID> tempList = null;
    for(Sales_Contract__c sc : Trigger.new)
    {
        tempList = new List<ID>();
        if(sc.UserID__c != UserInfo.getUserId())
            tempList.add(sc.UserID__c);
        if(sc.Level1__c != null)
            tempList.add(sc.Level1__c);
        if(sc.Level2__c != null)
            tempList.add(sc.Level2__c);
        if(sc.Level3__c != null)
            tempList.add(sc.Level3__c);
        if(sc.Final_Approver__c != null)
            tempList.add(sc.Final_Approver__c);
            
        usersManagerMap.put(sc.UserID__c, tempList);
    }
    
    for(CallidusDataSource__c[] cdsList : [select Id, UserID__c from CallidusDataSource__c where UserID__c in :usersManagerMap.keySet()])
    {
        for(CallidusDataSource__c cds : cdsList)
        {
            List<ID> managersList = usersManagerMap.get(cds.UserID__c);
            for(Id manager : managersList)
            {
                //Give access to the user to access his Plan Document
                CallidusDataSource__Share cdsShare  = new CallidusDataSource__Share();
                  
                cdsShare.ParentId = cds.Id;
                cdsShare.UserOrGroupId = manager;
                    
                // Set the access level.
                cdsShare.AccessLevel = 'edit';
                 
                // Set rowCause to 'manual' for manual sharing.
                // This line can be omitted as 'manual' is the default value for sharing objects.
                cdsShare.RowCause = Schema.CallidusDataSource__Share.RowCause.Manual;
                  
                // Insert the sharing record and capture the save result. 
                // The false parameter allows for partial processing if multiple records passed 
                // into the operation.
                
                //if(UserInfo.getUserId() != cdsShare.UserOrGroupId)
                dataSourceSharingList.add(cdsShare);
                    
                if(dataSourceSharingList.size() == 200)
                {
                    insert dataSourceSharingList;
                    dataSourceSharingList.clear();
                }
                
            }
        }
    }
    
    if(dataSourceSharingList.size() > 0)
    {
        insert dataSourceSharingList;
        dataSourceSharingList.clear();
    } */
    
    if(Trigger.isInsert)
    {
        List<Sales_Contract__c> newSCList = Trigger.newMap.values();
        
        for(Sales_Contract__c s : newSCList)
        {
            if(s.Status__c == 'Distributed' || s.Status__c == 'Published')
            {
                //Give access to the user to access his Plan Document
                Sales_Contract__Share scShare  = new Sales_Contract__Share();
                  
                scShare.ParentId = s.Id;
                // Set the ID of user or group being granted access.
                if(s.Status__c == 'Published')              
                    scShare.UserOrGroupId = s.UserID__c;
                else
                    scShare.UserOrGroupId = s.Level1__c;
                    
                // Set the access level.
                scShare.AccessLevel = 'edit';
                 
                // Set rowCause to 'manual' for manual sharing.
                // This line can be omitted as 'manual' is the default value for sharing objects.
                scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
                  
                // Insert the sharing record and capture the save result. 
                // The false parameter allows for partial processing if multiple records passed 
                // into the operation.
                if(UserInfo.getUserId() != scShare.UserOrGroupId)
                    shareContractList.add(scShare);
                    
                if(shareContractList.size() == 200)
                {
                    insert shareContractList;
                    shareContractList.clear();
                }
            }
            
        }
        if(shareContractList.size() > 0)
        {
            insert shareContractList;
            shareContractList.clear();
        }
        
    }//end of if(Trigger.isInsert)
    
    if(Trigger.isUpdate)
    {
        for(Sales_Contract__c recallSCObj : Trigger.new)
        {
            if(recallSCObj.Is_Recalled__c ==  true)
            {
                Task[] recallT = [select id from Task where whatid = :recallSCObj.id];
                if(recallT.size() > 0)
                    delete recallT;
            }
        }    
        
        List<Sales_Contract__c> newSCList = Trigger.newMap.values();
        
        for(Sales_Contract__c s : newSCList)
        {
            if(s.Status__c == 'Distributed')
            {
                //Give access to the user to access his Plan Document
                Sales_Contract__Share scShare  = new Sales_Contract__Share();
                  
                scShare.ParentId = s.Id;

                scShare.UserOrGroupId = s.Level1__c;
                    
                // Set the access level.
                scShare.AccessLevel = 'edit';
                 
                // Set rowCause to 'manual' for manual sharing.
                // This line can be omitted as 'manual' is the default value for sharing objects.
                scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
                  
                // Insert the sharing record and capture the save result. 
                // The false parameter allows for partial processing if multiple records passed 
                // into the operation.
                if(UserInfo.getUserId() != scShare.UserOrGroupId)
                    shareContractList.add(scShare);
                    
                if(shareContractList.size() == 200)
                {
                    insert shareContractList;
                    shareContractList.clear();
                }
            }
            
        }
        if(shareContractList.size() > 0)
        {
            insert shareContractList;
            shareContractList.clear();
        }
        
        String[] skipStatusList = new String[]{'Distributed', 'Draft', 'Viewed', 'Accepted', 'Rejected', 'Reviewed', 'Submitted to Field Ops', 'Inquiry Submitted', 'Inquiry Pending', 'Inquiry Rejected'};
        for(Sales_Contract__c[] sc: [select Id, Name, (Select ActorId, OriginalActorId, RemindersSent, StepStatus, IsPending from ProcessSteps where IsPending = true), FirstName__c, LastName__c, Status__c, RequiredReturnDate__c, Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Final_Approver__c, Final_Approver_Date__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c, ownerId, CreatedById, UserID__c from Sales_Contract__c where Id in :Trigger.new and Status__c not in :skipStatusList and Is_Recalled__c = false])
        {
            scSize = 0;
            for(Sales_Contract__c s: sc)
            {
                scSize++;
                if(s.Status__c.indexOf('Plan Rejected') != -1)
                {
                    Task t = new Task();
                    t.OwnerId = s.CreatedById;
                    t.WhatId = s.Id;
                    
                    t.Subject = s.FirstName__c+' '+s.LastName__c+'\'s Plan Document has been Rejected';
                    t.Description = s.FirstName__c+' '+s.LastName__c+'\'s Plan Document has been Rejected';
                    
                    t.Status = 'NotStarted';
                    t.Type = 'Email';
                    t.ActivityDate = Date.today();
                    t.ReminderDateTime = DateTime.now();
                    t.IsReminderSet = true;
                    t.Priority = 'High';
                    
                    taskList.add(t);
                }
               
                if(s.Status__c.indexOf('Plan Approved') != -1)
                {
                    shareId = '';
                    
                    for(ProcessInstanceHistory instanceHistory : s.ProcessSteps)
                    {
                        if(instanceHistory.IsPending)
                        {
                            if(s.Level1__c == instanceHistory.ActorId)
                            {
                                if(s.Level2__c != null)
                                {
                                    shareId = s.Level2__c;
                                    dt = s.Level2_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level2__c == instanceHistory.ActorId)
                            {
                                if(s.Level3__c != null)
                                {
                                    shareId = s.Level3__c;
                                    dt = s.Level3_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level3__c == instanceHistory.ActorId)
                            {
                                if(s.Level4__c != null)
                                {
                                    shareId = s.Level4__c;
                                    dt = s.Level4_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level4__c == instanceHistory.ActorId)
                            {
                                if(s.Level5__c != null)
                                {
                                    shareId = s.Level5__c;
                                    dt = s.Level5_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level5__c == instanceHistory.ActorId)
                            {
                                if(s.Level6__c != null)
                                {
                                    shareId = s.Level6__c;
                                    dt = s.Level6_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level6__c == instanceHistory.ActorId)
                            {
                                if(s.Level7__c != null)
                                {
                                    shareId = s.Level7__c;
                                    dt = s.Level7_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level7__c == instanceHistory.ActorId)
                            {
                                if(s.Level8__c != null)
                                {
                                    shareId = s.Level8__c;
                                    dt = s.Level8_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level8__c == instanceHistory.ActorId)
                            {
                                if(s.Level9__c != null)
                                {
                                    shareId = s.Level9__c;
                                    dt = s.Level9_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level9__c == instanceHistory.ActorId)
                            {
                                if(s.Level10__c != null)
                                {
                                    shareId = s.Level10__c;
                                    dt = s.Level10_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level10__c == instanceHistory.ActorId)
                            {
                                if(s.Level11__c != null)
                                {
                                    shareId = s.Level11__c;
                                    dt = s.Level11_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level11__c == instanceHistory.ActorId)
                            {
                                if(s.Level12__c != null)
                                {
                                    shareId = s.Level12__c;
                                    dt = s.Level12_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level12__c == instanceHistory.ActorId)
                            {
                                if(s.Level13__c != null)
                                {
                                    shareId = s.Level13__c;
                                    dt = s.Level13_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level13__c == instanceHistory.ActorId)
                            {
                                if(s.Level14__c != null)
                                {
                                    shareId = s.Level14__c;
                                    dt = s.Level14_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level14__c == instanceHistory.ActorId)
                            {
                                if(s.Level15__c != null)
                                {
                                    shareId = s.Level15__c;
                                    dt = s.Level15_Due_Date__c;
                                }
                                else if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            }
                            else if(s.Level15__c == instanceHistory.ActorId)
                            {
                                if(s.Final_Approver__c != null)
                                {
                                    shareId = s.Final_Approver__c;
                                    dt = s.Final_Approver_Date__c;
                                }
                            } 
                        }
                        
                        break;
                    }//end of for(ProcessInstanceHistory ....)
                    
                    if(shareId != '')
                    {
                        Task t = new Task();
                        t.OwnerId = shareId;
                        t.WhatId = s.Id;
                        
                        t.Subject = s.FirstName__c+' '+s.LastName__c+'\'s Plan Document has been Approved';
                        t.Description = s.FirstName__c+' '+s.LastName__c+'\'s Plan Document has been Approved.';
                        
                        t.Status = 'NotStarted';
                        t.Type = 'Email';
                        t.ActivityDate = dt;
                        String remDateTime = dt+' 08:00:00';
                        t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                        t.IsReminderSet = true;
                        t.Priority = 'High';
                        
                        taskList.add(t);
                        
                        Sales_Contract__Share scShare  = new Sales_Contract__Share();
                          
                        scShare.ParentId = s.Id;
                          
                        // Set the ID of user or group being granted access.
                        scShare.UserOrGroupId = shareId;                  
        
                        scShare.AccessLevel = 'Edit';
                          
                        // Set rowCause to 'manual' for manual sharing.
                        // This line can be omitted as 'manual' is the default value for sharing objects.
                        scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
                        shareContractList.add(scShare);                  
                    }
                }
    
                if(s.Status__c == 'Published' && s.UserID__c != UserInfo.getUserId())
                {
                    Task t = new Task();
                    t.OwnerId = s.UserID__c;
                    t.WhatId = s.Id;
                    t.Subject = 'Plan Document Published';
                    t.Description = 'Plan Document Published.';
                    t.Status = 'NotStarted';
                    t.Type = 'Email';
                    t.ActivityDate = s.RequiredReturnDate__c;
                    String remDateTime = s.RequiredReturnDate__c+' 08:00:00';
                    t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                    t.IsReminderSet = true;
                    t.Priority = 'High';
                    
                    taskList.add(t);
    
                    Sales_Contract__Share scShare  = new Sales_Contract__Share();
                      
                    scShare.ParentId = s.Id;
                      
                      // Set the ID of user or group being granted access.
                
                    scShare.UserOrGroupId = s.UserID__c;
                      
                      
                      // Set the access level.
                    scShare.AccessLevel = 'Edit';
                      
                      // Set rowCause to 'manual' for manual sharing.
                      // This line can be omitted as 'manual' is the default value for sharing objects.
                    scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
                    shareContractList.add(scShare);
                }
                
                if(sc.size() == scSize)
                {
                    try
                    {
                        insert taskList;
                        insert shareContractList;
                    }
                    catch(Exception e)
                    {
                       
                    }
                    
                    if(shareContractList.size() > 0)
                        shareContractList.clear();
                    if(taskList.size() > 0)
                        taskList.clear();
                }
                //Sales_Contract__History history = new Sales_Contract__History(ParentId = s.Id);
            }                                        
        }
    }
}